package xyz.syyrjx.registry.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.syyrjx.code.SyyrjxRpcCoder;
import xyz.syyrjx.exception.SyyrjxRpcRegistryException;
import xyz.syyrjx.exception.SyyrjxRpcRemoteException;
import xyz.syyrjx.response.SyyrjxRpcResponse;

/**
 * @author 大地崩坏苍蝇兽
 * @date 2023/1/16 - 18:39
 */
public class SyyrjxRpcRegistryClientHandler extends SimpleChannelInboundHandler<String> {

    private final static Logger LOGGER = LoggerFactory.getLogger(SyyrjxRpcRegistryClientHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        SyyrjxRpcResponse response = SyyrjxRpcCoder.StringToObject(s);
        if (!response.isFlag()) {
            throw new SyyrjxRpcRegistryException(SyyrjxRpcRegistryException.REGISTRY_CENTER_CLUSTER_ERROR);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.writeAndFlush(SyyrjxRpcResponse.providerFail(SyyrjxRpcRemoteException.SERVER_ERROR).toSerializableString());
        LOGGER.error(cause.getMessage());
    }
}
